package cm.tl.pms.util;


import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileOutputStream;
import java.net.URI;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static cm.tl.pms.common.constant.ConstantConfig.getUploadFilePath;
import static cm.tl.pms.common.constant.ConstantConfig.getUploadFilePrefix;

/**
 * 文件工具类
 *
 * @author w7h1te_ywq
 * @version 1.0.0
 * @date 2024-01-08 17:04
 */
@Slf4j
public class FileUtil {


    //文件上传
    public static String uploadFile(MultipartFile file) {
        //获取文件上传路径
//        String path = "/opt/bc_digital_manage/filetomcat/webapps/file/toVoice/";

        // http://36.110.223.95:8082/file/data_merger_pro/174243744024164750.jpeg
        String path = getUploadFilePrefix() + getUploadFilePath();

//    	String path = "D:\\file";
        String originalFilename = file.getOriginalFilename();
        //获取文件后缀
        String substring = originalFilename.substring(originalFilename.lastIndexOf("."));
        File targetFile;
        //拼接新文件名(时间戳+5位数随机数)
        String photoFileName = System.currentTimeMillis() + RandomUtil.getAllNum(5) + substring;
        try {
            File upload = new File(path);
            if (!upload.exists()) {
                upload.mkdirs();
            }
            targetFile = new File(path, photoFileName);
            //将上传的文件写到服务器上指定的目录。
            file.transferTo(targetFile);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return getUploadFilePath() + "/" + photoFileName;
    }


    //文件上传
    public static String uploadFile(MultipartFile file, String fileSavePath) {
        //获取文件上传路径
//        String path = "/opt/bc_digital_manage/filetomcat/webapps/file/toVoice/";
        String path = getUploadFilePrefix();
        String projectPath = "";

        if (StringUtils.isNotBlank(fileSavePath)) {
            projectPath = fileSavePath;
        } else {
            projectPath = getUploadFilePath();
        }
        path += projectPath;
        String originalFilename = file.getOriginalFilename();
        //获取文件后缀
        String substring = originalFilename.substring(originalFilename.lastIndexOf("."));
        File targetFile;
        //拼接新文件名(时间戳+5位数随机数)
        String photoFileName = System.currentTimeMillis() + RandomUtil.getAllNum(5) + substring;
        try {
            File upload = new File(path);
            if (!upload.exists()) {
                upload.mkdirs();
            }
            targetFile = new File(path, photoFileName);
            //将上传的文件写到服务器上指定的目录。
            file.transferTo(targetFile);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return projectPath + "/" + photoFileName;
    }

    /**
     * 根据文件大小的不同范围，进行相应的转换并返回带有单位的字符串
     *
     * @param bytes
     * @return
     */
    public static String formatSize(long bytes) {
        if (bytes < 1024) {
            return bytes + " B";
        } else if (bytes < 1024 * 1024) {
            return Math.round(bytes / 1024.0) + " KB";
        } else if (bytes < 1024 * 1024 * 1024) {
            return Math.round(bytes / (1024.0 * 1024.0)) + " MB";
        } else {
            return Math.round(bytes / (1024.0 * 1024.0 * 1024.0)) + " GB";
        }
    }


    /**
     * 获取指定类型的文件单位大小
     *
     * @param bytes
     * @return
     */
    public static String formatSize(long bytes, String units) {
        switch (units) {
            case "B":
                return bytes + " B";
            case "K":
                return Math.round(bytes / 1024.0) + " KB";
            case "M":
                return Math.round(bytes / (1024.0 * 1024.0)) + " MB";
            case "G":
                return Math.round(bytes / (1024.0 * 1024.0 * 1024.0)) + " GB";
            default:
                return bytes + " B";
        }
    }


    //文件批量上传
    public static List<Map<String, String>> uploadFileList(MultipartFile[] files) {
        //获取文件上传路径
        List<Map<String, String>> list = new ArrayList<>();

        //判断file数组不能为空并且长度大于0
        log.info("files.length :" + files.length);
        if (files != null && files.length > 0) {
            Map<String, String> map = new HashMap<>();
            //循环获取file数组中的文件
            for (int i = 0; i < files.length; i++) {
                MultipartFile file = files[i];
                //保存文件
                String pathA = uploadFile(file);
                if (StringUtils.isNotBlank(pathA)) {
                    map.put("fileName", file.getOriginalFilename());
                    map.put("fileUrl", pathA);
                }
            }
            list.add(map);
        }
        return list;
    }

    //根据后缀归类
    public static Integer getMediaTypeByExt(String ext) {
        int mediaType;
        switch (ext) {
            case "doc":
            case "docx":
            case "pdf":
            case "xls":
            case "xlsx":
            case "txt":
                mediaType = 4; // 文档类型
                break;
            case "mp4":
            case "avi":
            case "mov":
                mediaType = 2; // 视频类型
                break;
            case "mp3":
            case "wav":
            case "ogg":
                mediaType = 3; // 音频类型
                break;
            case "jpg":
            case "jpeg":
            case "png":
                mediaType = 1; // 图片类型
                break;
            default:
                mediaType = 0; // 其他类型
                break;
        }
        return mediaType;
    }

    public static void main(String[] args) {
        System.out.println("originalFilename.png".substring("originalFilename.png".lastIndexOf(".") + 1));

        downloadAndUpImage("http://36.110.223.95:8082/file/data_merger_pro/174243744024164750.jpeg");
    }


    public static String downloadAndUpImage(String imageUrl) {
        HttpGet request = null;

        try {
            HttpClient client = HttpClients.custom().build();
            request = new HttpGet(new URI(imageUrl));
            HttpResponse response = client.execute(request);

            // 检查响应状态码
            if (response.getStatusLine().getStatusCode() == 200) {
                // 获取响应实体
                HttpEntity entity = response.getEntity();

                // 将响应实体转换为字节数组
                byte[] imageData = EntityUtils.toByteArray(entity);

                String path = getUploadFilePrefix() + getUploadFilePath();

                //String path = "/Users/yangyanping/Downloads";

                //拼接新文件名(时间戳+5位数随机数)
                String photoFileName = "face" + System.currentTimeMillis() + RandomUtil.getAllNum(5) + ".jpg";

                String destinationFilePath = path + "/" + photoFileName;
                // 创建本地文件
                File destinationFile = new File(destinationFilePath);
                try (FileOutputStream fos = new FileOutputStream(destinationFile)) {
                    // 将图片数据写入本地文件
                    fos.write(imageData);
                }

                log.info("图片已成功保存到：{}", destinationFilePath);

                return photoFileName;
            } else {
                throw new RuntimeException("下载图片失败");
            }
        } catch (Exception e) {
            log.error("downloadAndUpImage", e);
            throw new RuntimeException("下载图片失败", e);
        }
    }
}
